package com.yunhe.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

//类似拦截器AOP横切
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.authorizeRequests()
                //首页所有人可以访问，功能只有对应有权限的人才能访问
                .antMatchers("/index").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")//是VIP1才可以访问level1下的所有资源
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
                //......可以写多个

        //没有权限会自动跳转登入页面，设置了根据用户显示页面后，这个就意义不大了
        http.formLogin().loginPage("/login");
        //注销
        http.logout().logoutSuccessUrl("/index");
        //防止网站工具（POST）
        http.csrf().disable();
        //开启记住我功能,保存cookie，默认保存14天，自定义接收前端的参数
        http.rememberMe().rememberMeParameter("remember");

    }

    //从内存临时储存，真是开发是连接真实数据库
    protected void configure(AuthenticationManagerBuilder auth) throws  Exception{
                                     //passwordEncoder密码加密编码
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                //内存存储用户和密码，roles是
                .withUser("zs").password(new BCryptPasswordEncoder().encode("zs")).roles("vip1","vip2")//vip1和vip8都可以访问
                .and()
                .withUser("ls").password(new BCryptPasswordEncoder().encode("ls")).roles("vip2")
                .and()
                .withUser("ww").password(new BCryptPasswordEncoder().encode("ww")).roles("vip1","vip3");

    }
}
